package splash;

import utility.Sprite;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import coganh.Activity.MainMenu;
import coganh.Activity.R;

public class SplashThread extends Thread {

	private Bitmap b;

	private SplashSprite mspSprite;

	private boolean mRun;

	private SurfaceHolder mSurfaceHolder;

	private Resources res;
	private SplashView mSplashView;

	public SplashThread(SplashView splashView, Context context) {
		// get handles to some important objects
		this.res = context.getResources();
		mSplashView = splashView;
		mSurfaceHolder = mSplashView.getHolder();
		mspSprite = new SplashSprite();
		mspSprite.setOriented(Sprite.ORIENTED_HORIZONTAL);
		mspSprite.setDelay(5000);
		if (b == null)
			b = BitmapFactory.decodeResource(res, R.drawable.explosion);
		mspSprite.Initialize(b, 120, 160, 24, 20, false);
		mspSprite.setxPost(240);
		mspSprite.setyPost(400);
	}

	@Override
	public void run() {
		while (mRun) {
			Canvas c = null;
			try {
				c = mSurfaceHolder.lockCanvas();
				synchronized (mSurfaceHolder) {
					doDraw(c);
					updatePhysics();
					if (mspSprite.isDispose())
						this.setRunning(false);
				}
			} catch (Exception e) {
				System.out.println(e.getStackTrace());
			} finally {
				if (c != null) {
					mSurfaceHolder.unlockCanvasAndPost(c);
				}
			}
		}
		Intent intent = new Intent();
		intent.setClass(mSplashView.getContext(), MainMenu.class);
		mSplashView.getContext().startActivity(intent);
	}

	/**
	 * Draws to the provided Canvas.
	 */
	private void doDraw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		mspSprite.draw(canvas);
		canvas.restore();
	}

	private void updatePhysics() {
		long now = System.currentTimeMillis();
		mspSprite.Update(now);
	}

	public boolean ismRun() {
		return mRun;
	}

	public void setRunning(boolean b) {
		mRun = b;
	}

	public void doTouch(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			this.setRunning(false);
		}
	}
}
